package com.web.task;

import com.web.dao.*;
import com.web.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import static com.web.manager.CoreManager.countTotalVal;
import static java.math.BigDecimal.ROUND_HALF_DOWN;

/**
 *
 * @author FDjavaone
 * @date 2017/9/18
 */

@Component
@Configurable
@EnableScheduling
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class MskAtomicFissionJob {
    @Autowired
    private PlatformMapper platformMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private PoundageConfigMapper poundageConfigMapper;
    @Autowired
    private ProfitConfigMapper profitConfigMapper;
    @Autowired
    private MskDetailMapper mskDetailMapper;
    @Autowired
    private ProfitDetailMapper profitDetailMapper;
    @Autowired
    private ConsumptionDetailMapper consumptionDetailMapper;
    @Autowired
    private CompanyCompanyMsDetailMapper companyCompanyMsDetailMapper;
    @Autowired
    private CompanyMarketDetailMapper companyMarketDetailMapper;
    @Autowired
    private CompanyPoundageDetailMapper companyPoundageDetailMapper;
    @Autowired
    private CompanyMarketMsDetailMapper companyMarketMsDetailMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private CompanyReportMapper companyReportMapper;

    @Scheduled(cron = "*/10 * * * * ?")
    public void atomicFission() throws Exception {
        try {
            log.info("裂变监控开始");
            //获取当前平台信息
            Platform platform = platformMapper.selectByPrimaryKey(1L);
            Date date=new Date();
            //获取msk交易策略
            PoundageConfig poundageConfig = poundageConfigMapper.selectByPrimaryKey(1L);
            //获取裂变时自动交易比例配置
            ProfitConfig profitConfig=profitConfigMapper.selectByPrimaryKey(1L);

            if(platform.getMarketMsk().compareTo(new BigDecimal("0"))==0){

            }else{
                //msk当前市场价格
                BigDecimal newPrice = platform.getMarketFundPool().divide(platform.getMarketMsk(),2,ROUND_HALF_DOWN);

                //判断当前msk市场价格是否需要裂变
                if (newPrice.compareTo(new BigDecimal("2")) != -1) {
                    //需要裂变
                    log.info("当前msk价格为："+newPrice+"，需要裂变！");

                    int n=newPrice.intValue();
                    newPrice=newPrice.divide(new BigDecimal(n),2,ROUND_HALF_DOWN);

                    log.info("MSK数量需要裂变为当前的："+n+"倍！");

                    //市场msk数量增至n倍
                    platformMapper.atomicFission(n,1L);
                    CompanyMarketMsDetail companyMarketMsDetail=new CompanyMarketMsDetail();
                    companyMarketMsDetail.setCreateTime(date);
                    companyMarketMsDetail.setModifyTime(date);
                    companyMarketMsDetail.setContent("MS裂变");
                    companyMarketMsDetail.setDetail("市场MS增至"+n+"倍");
                    companyMarketMsDetail.setBal(platformMapper.selectByPrimaryKey(1L).getMarketMsk().toString());
                    companyMarketMsDetail.setFromNum("");
                    companyMarketMsDetail.setName("系统");
                    companyMarketMsDetail.setPhone("");
                    companyMarketMsDetail.setDescription("市场MS增至"+n+"倍");
                    companyMarketMsDetailMapper.insertSelective(companyMarketMsDetail);


                    //取出所以msk不为零的账户
                    List<Account> accounts=accountMapper.findMskNotZero();


                    for(Account a:accounts){
                        Member member=memberMapper.selectByPrimaryKey(a.getmId());
                        //每个用户的msk数量增至 n倍，卖出完成增长的msk的相应配置比例
                        BigDecimal total=a.getMsk().multiply(new BigDecimal(n));
                        int sale=total.multiply(profitConfig.getFission()).divide(new BigDecimal(100)).intValue();
                        a.setModifyTime(date);
                        a.setMsk(total.subtract(new BigDecimal(sale)));
                        accountMapper.updateByPrimaryKeySelective(a);
                        //裂变时msk增加明细
                        MskDetail fissionMsk=new MskDetail();
                        fissionMsk.setTransactionNum(total);
                        fissionMsk.setTransactionPrice(newPrice);
                        fissionMsk.setModifyTime(date);
                        fissionMsk.setCreateTime(date);
                        fissionMsk.setType(1);
                        fissionMsk.setContent("裂变");
                        fissionMsk.setDetail("裂变，MS增长至" +total);
                        fissionMsk.setaId(a.getId());
                        fissionMsk.setBal(total.toString());
                        fissionMsk.setName(member.getName());
                        fissionMsk.setPhone(member.getPhone());
                        mskDetailMapper.insertSelective(fissionMsk);

                        //用户的msk账户减少对应msk
                        MskDetail mskDetail = new MskDetail();
                        mskDetail.setTransactionNum(new BigDecimal(sale));
                        mskDetail.setTransactionPrice(newPrice);
                        mskDetail.setModifyTime(date);
                        mskDetail.setCreateTime(date);
                        mskDetail.setType(2);
                        mskDetail.setContent("裂变卖出");
                        mskDetail.setDetail("MS:-" + new BigDecimal(sale));
                        mskDetail.setaId(a.getId());
                        mskDetail.setBal(accountMapper.selectByPrimaryKey(a.getId()).getMsk().toString());
                        mskDetail.setName(member.getName());
                        mskDetail.setPhone(member.getPhone());
                        mskDetailMapper.insertSelective(mskDetail);

                        //公司msk账户增加对应数量msk
                        platformMapper.companyMskAdd(new BigDecimal(sale), 1L);
                        CompanyCompanyMsDetail companyCompanyMsDetail=new CompanyCompanyMsDetail();
                        companyCompanyMsDetail.setCreateTime(date);
                        companyCompanyMsDetail.setModifyTime(date);
                        companyCompanyMsDetail.setContent("MS裂变，用户卖出自己的对应比例MS，公司MS增加");
                        companyCompanyMsDetail.setDetail("+"+sale);
                        companyCompanyMsDetail.setBal(platformMapper.selectByPrimaryKey(1L).getCompanyMsk().toString());
                        companyCompanyMsDetail.setDescription("MS裂变，用户卖出自己的对应比例MS，公司MS增加");
                        companyCompanyMsDetail.setFromNum("");
                        companyCompanyMsDetail.setName(member.getName());
                        companyCompanyMsDetail.setPhone(member.getPhone());
                        companyCompanyMsDetailMapper.insertSelective(companyCompanyMsDetail);

                        //市场msk账户减少对应数量msk
                        platformMapper.marketMskSubtract(new BigDecimal(sale), 1L);
                        CompanyMarketMsDetail companyMarketMsDetail1=new CompanyMarketMsDetail();
                        companyMarketMsDetail1.setCreateTime(date);
                        companyMarketMsDetail1.setModifyTime(date);
                        companyMarketMsDetail1.setContent("MS裂变，用户卖出自己的对应比例MS，市场MS减少");
                        companyMarketMsDetail1.setDetail("-"+sale);
                        companyMarketMsDetail1.setBal(platformMapper.selectByPrimaryKey(1L).getMarketMsk().toString());
                        companyMarketMsDetail1.setFromNum("");
                        companyMarketMsDetail1.setName(member.getName());
                        companyMarketMsDetail1.setPhone(member.getPhone());
                        companyMarketMsDetail1.setDescription("MS裂变，用户卖出自己的对应比例MS，市场MS减少");
                        companyMarketMsDetailMapper.insertSelective(companyMarketMsDetail1);


                        CompanyReport companyReport=new CompanyReport();

                        companyReport.setCreateTime(date);
                        companyReport.setModifyTime(date);
                        companyReport.setReserve1("MS裂变自动卖出相应比例");

                        BigDecimal withdrawRecord=new BigDecimal("0");
                        BigDecimal marketRecord=new BigDecimal("0");
                        BigDecimal consumeRecord=new BigDecimal("0");
                        BigDecimal profitRecord=new BigDecimal("0");

                        //市场资金池扣除对应金额用于支付
                        companyReport.setMarketFund("-" + newPrice.multiply(new BigDecimal(sale)));
                        marketRecord = new BigDecimal(companyReport.getMarketFund());
                        companyReport.setMarketFund((companyReport.getMarketFund()!=null?companyReport.getMarketFund():"") + "\r\n=" + platformMapper.selectByPrimaryKey(1L).getMarketFundPool().add(marketRecord));


                        platformMapper.marketFundPoolSubtract(newPrice.multiply(new BigDecimal(sale)), 1L);
                        CompanyMarketDetail companyMarketDetail=new CompanyMarketDetail();
                        companyMarketDetail.setCreateTime(date);
                        companyMarketDetail.setModifyTime(date);
                        companyMarketDetail.setContent("MS裂变，用户卖出自己的对应比例MS，市场资金池支付，金额减少");
                        companyMarketDetail.setDetail("-"+newPrice.multiply(new BigDecimal(sale)));
                        companyMarketDetail.setName(member.getName());
                        companyMarketDetail.setPhone(member.getPhone());
                        companyMarketDetail.setFromNum("");
                        companyMarketDetail.setBal(platformMapper.selectByPrimaryKey(1L).getMarketFundPool().toString());
                        companyMarketDetail.setDescription("MS裂变，用户卖出自己的对应比例MS，市场资金池支付，金额减少");
                        companyMarketDetailMapper.insertSelective(companyMarketDetail);

                        //公司手续费池资金增加
                        companyReport.setWithdrawPoundage("+" + newPrice.multiply(new BigDecimal(sale)).multiply(poundageConfig.getMskSale()).divide(new BigDecimal("100"),2, ROUND_HALF_DOWN));
                        withdrawRecord = new BigDecimal(companyReport.getWithdrawPoundage());
                        companyReport.setWithdrawPoundage("+"+withdrawRecord+"\n\r="+platformMapper.selectByPrimaryKey(1L).getPoundagePool().add(withdrawRecord));


                        platformMapper.poundagePoolAdd(newPrice.multiply(new BigDecimal(sale)).multiply(poundageConfig.getMskSale()).divide(new BigDecimal("100"),2, ROUND_HALF_DOWN), 1L);
                        CompanyPoundageDetail companyPoundageDetail=new CompanyPoundageDetail();
                        companyPoundageDetail.setCreateTime(date);
                        companyPoundageDetail.setModifyTime(date);
                        companyPoundageDetail.setContent("MS裂变卖出手续费收益增加");
                        companyPoundageDetail.setDetail("+"+newPrice.multiply(new BigDecimal(sale)).multiply(poundageConfig.getMskSale()).divide(new BigDecimal("100"),2, ROUND_HALF_DOWN));
                        companyPoundageDetail.setBal(platformMapper.selectByPrimaryKey(1L).getCompanyProfitPool().toString());
                        companyPoundageDetail.setFromNum("");
                        companyPoundageDetail.setDescription("MS裂变卖出手续费收益增加");
                        companyPoundageDetail.setName(member.getName());
                        companyPoundageDetail.setPhone(member.getPhone());
                        companyPoundageDetailMapper.insertSelective(companyPoundageDetail);

                        //用户利润账户增加
                        companyReport.setProfitBal("+" + newPrice.multiply(new BigDecimal(sale)).multiply(poundageConfig.getMskSaleP()).divide(new BigDecimal("100"),2, ROUND_HALF_DOWN));
                        profitRecord = new BigDecimal(companyReport.getProfitBal());
                        companyReport.setProfitBal("+"+profitRecord+"\n\r="+accountMapper.countProfitNum().add(profitRecord));


                        accountMapper.profitAdd(newPrice.multiply(new BigDecimal(sale)).multiply(poundageConfig.getMskSaleP()).divide(new BigDecimal("100"),2, ROUND_HALF_DOWN), a.getId());
                        ProfitDetail profitDetailUp = new ProfitDetail();
                        profitDetailUp.setModifyTime(date);
                        profitDetailUp.setCreateTime(date);
                        profitDetailUp.setContent("卖出MS");
                        profitDetailUp.setDetail("+" + newPrice.multiply(new BigDecimal(sale)).multiply(poundageConfig.getMskSaleP()).divide(new BigDecimal("100"),2,ROUND_HALF_DOWN));
                        profitDetailUp.setBal(accountMapper.selectByPrimaryKey(a.getId()).getProfit().toString());
                        profitDetailUp.setFromNum("");
                        profitDetailUp.setName(member.getName());
                        profitDetailUp.setPhone(member.getPhone());
                        profitDetailUp.setaId(a.getId());

                        profitDetailMapper.insertSelective(profitDetailUp);
                        //用户消费账户增加
                        companyReport.setConsumeBal("+" + newPrice.multiply(new BigDecimal(sale)).multiply(poundageConfig.getMskSaleC()).divide(new BigDecimal("100"),2,ROUND_HALF_DOWN));
                        consumeRecord = new BigDecimal(companyReport.getConsumeBal());
                        companyReport.setConsumeBal("+"+consumeRecord+"\n\r="+accountMapper.countConsumeNum().add(consumeRecord));


                        accountMapper.consumptionAdd(newPrice.multiply(new BigDecimal(sale)).multiply(poundageConfig.getMskSaleC()).divide(new BigDecimal("100"),2,ROUND_HALF_DOWN), a.getId());
                        ConsumptionDetail consumptionDetail = new ConsumptionDetail();
                        consumptionDetail.setModifyTime(date);
                        consumptionDetail.setCreateTime(date);
                        consumptionDetail.setContent("卖出MS");
                        consumptionDetail.setDetail("+" + newPrice.multiply(new BigDecimal(sale)).multiply(poundageConfig.getMskSaleC()).divide(new BigDecimal("100"),2,ROUND_HALF_DOWN));
                        consumptionDetail.setaId(a.getId());
                        consumptionDetail.setBal(accountMapper.selectByPrimaryKey(a.getId()).getConsumption().toString());
                        consumptionDetail.setFromNum("");
                        consumptionDetail.setName(member.getName());
                        consumptionDetail.setPhone(member.getPhone());
                        consumptionDetailMapper.insertSelective(consumptionDetail);
                        companyReport.setTotal(marketRecord.add(withdrawRecord).add(profitRecord).add(consumeRecord).toString()+"\n\r="+countTotalVal(companyReport));
                        companyReportMapper.insertSelective(companyReport);
                    }

                }
            }


            log.info("裂变监控结束");
        }catch (Exception e){
            e.printStackTrace();

        }

    }

}
